home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / htmllib.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  12.2 KB  |  476 lines

  1. """HTML 2.0 parser.
  2.  
  3. See the HTML 2.0 specification:
  4. http://www.w3.org/hypertext/WWW/MarkUp/html-spec/html-spec_toc.html
  5. """
  6.  
  7.  
  8. from sgmllib import SGMLParser
  9. from formatter import AS_IS
  10.  
  11. __all__ = ["HTMLParser"]
  12.  
  13. class HTMLParser(SGMLParser):
  14.     """This is the basic HTML parser class.
  15.  
  16.     It supports all entity names required by the HTML 2.0 specification
  17.     RFC 1866.  It also defines handlers for all HTML 2.0 and many HTML 3.0
  18.     and 3.2 elements.
  19.  
  20.     """
  21.  
  22.     from htmlentitydefs import entitydefs
  23.  
  24.     def __init__(self, formatter, verbose=0):
  25.         """Creates an instance of the HTMLParser class.
  26.  
  27.         The formatter parameter is the formatter instance associated with
  28.         the parser.
  29.  
  30.         """
  31.         SGMLParser.__init__(self, verbose)
  32.         self.formatter = formatter
  33.         self.savedata = None
  34.         self.isindex = 0
  35.         self.title = None
  36.         self.base = None
  37.         self.anchor = None
  38.         self.anchorlist = []
  39.         self.nofill = 0
  40.         self.list_stack = []
  41.  
  42.     # ------ Methods used internally; some may be overridden
  43.  
  44.     # --- Formatter interface, taking care of 'savedata' mode;
  45.     # shouldn't need to be overridden
  46.  
  47.     def handle_data(self, data):
  48.         if self.savedata is not None:
  49.             self.savedata = self.savedata + data
  50.         else:
  51.             if self.nofill:
  52.                 self.formatter.add_literal_data(data)
  53.             else:
  54.                 self.formatter.add_flowing_data(data)
  55.  
  56.     # --- Hooks to save data; shouldn't need to be overridden
  57.  
  58.     def save_bgn(self):
  59.         """Begins saving character data in a buffer instead of sending it
  60.         to the formatter object.
  61.  
  62.         Retrieve the stored data via the save_end() method.  Use of the
  63.         save_bgn() / save_end() pair may not be nested.
  64.  
  65.         """
  66.         self.savedata = ''
  67.  
  68.     def save_end(self):
  69.         """Ends buffering character data and returns all data saved since
  70.         the preceding call to the save_bgn() method.
  71.  
  72.         If the nofill flag is false, whitespace is collapsed to single
  73.         spaces.  A call to this method without a preceding call to the
  74.         save_bgn() method will raise a TypeError exception.
  75.  
  76.         """
  77.         data = self.savedata
  78.         self.savedata = None
  79.         if not self.nofill:
  80.             data = ' '.join(data.split())
  81.         return data
  82.  
  83.     # --- Hooks for anchors; should probably be overridden
  84.  
  85.     def anchor_bgn(self, href, name, type):
  86.         """This method is called at the start of an anchor region.
  87.  
  88.         The arguments correspond to the attributes of the <A> tag with
  89.         the same names.  The default implementation maintains a list of
  90.         hyperlinks (defined by the HREF attribute for <A> tags) within
  91.         the document.  The list of hyperlinks is available as the data
  92.         attribute anchorlist.
  93.  
  94.         """
  95.         self.anchor = href
  96.         if self.anchor:
  97.             self.anchorlist.append(href)
  98.  
  99.     def anchor_end(self):
  100.         """This method is called at the end of an anchor region.
  101.  
  102.         The default implementation adds a textual footnote marker using an
  103.         index into the list of hyperlinks created by the anchor_bgn()method.
  104.  
  105.         """
  106.         if self.anchor:
  107.             self.handle_data("[%d]" % len(self.anchorlist))
  108.             self.anchor = None
  109.  
  110.     # --- Hook for images; should probably be overridden
  111.  
  112.     def handle_image(self, src, alt, *args):
  113.         """This method is called to handle images.
  114.  
  115.         The default implementation simply passes the alt value to the
  116.         handle_data() method.
  117.  
  118.         """
  119.         self.handle_data(alt)
  120.  
  121.     # --------- Top level elememts
  122.  
  123.     def start_html(self, attrs): pass
  124.     def end_html(self): pass
  125.  
  126.     def start_head(self, attrs): pass
  127.     def end_head(self): pass
  128.  
  129.     def start_body(self, attrs): pass
  130.     def end_body(self): pass
  131.  
  132.     # ------ Head elements
  133.  
  134.     def start_title(self, attrs):
  135.         self.save_bgn()
  136.  
  137.     def end_title(self):
  138.         self.title = self.save_end()
  139.  
  140.     def do_base(self, attrs):
  141.         for a, v in attrs:
  142.             if a == 'href':
  143.                 self.base = v
  144.  
  145.     def do_isindex(self, attrs):
  146.         self.isindex = 1
  147.  
  148.     def do_link(self, attrs):
  149.         pass
  150.  
  151.     def do_meta(self, attrs):
  152.         pass
  153.  
  154.     def do_nextid(self, attrs): # Deprecated
  155.         pass
  156.  
  157.     # ------ Body elements
  158.  
  159.     # --- Headings
  160.  
  161.     def start_h1(self, attrs):
  162.         self.formatter.end_paragraph(1)
  163.         self.formatter.push_font(('h1', 0, 1, 0))
  164.  
  165.     def end_h1(self):
  166.         self.formatter.end_paragraph(1)
  167.         self.formatter.pop_font()
  168.  
  169.     def start_h2(self, attrs):
  170.         self.formatter.end_paragraph(1)
  171.         self.formatter.push_font(('h2', 0, 1, 0))
  172.  
  173.     def end_h2(self):
  174.         self.formatter.end_paragraph(1)
  175.         self.formatter.pop_font()
  176.  
  177.     def start_h3(self, attrs):
  178.         self.formatter.end_paragraph(1)
  179.         self.formatter.push_font(('h3', 0, 1, 0))
  180.  
  181.     def end_h3(self):
  182.         self.formatter.end_paragraph(1)
  183.         self.formatter.pop_font()
  184.  
  185.     def start_h4(self, attrs):
  186.         self.formatter.end_paragraph(1)
  187.         self.formatter.push_font(('h4', 0, 1, 0))
  188.  
  189.     def end_h4(self):
  190.         self.formatter.end_paragraph(1)
  191.         self.formatter.pop_font()
  192.  
  193.     def start_h5(self, attrs):
  194.         self.formatter.end_paragraph(1)
  195.         self.formatter.push_font(('h5', 0, 1, 0))
  196.  
  197.     def end_h5(self):
  198.         self.formatter.end_paragraph(1)
  199.         self.formatter.pop_font()
  200.  
  201.     def start_h6(self, attrs):
  202.         self.formatter.end_paragraph(1)
  203.         self.formatter.push_font(('h6', 0, 1, 0))
  204.  
  205.     def end_h6(self):
  206.         self.formatter.end_paragraph(1)
  207.         self.formatter.pop_font()
  208.  
  209.     # --- Block Structuring Elements
  210.  
  211.     def do_p(self, attrs):
  212.         self.formatter.end_paragraph(1)
  213.  
  214.     def start_pre(self, attrs):
  215.         self.formatter.end_paragraph(1)
  216.         self.formatter.push_font((AS_IS, AS_IS, AS_IS, 1))
  217.         self.nofill = self.nofill + 1
  218.  
  219.     def end_pre(self):
  220.         self.formatter.end_paragraph(1)
  221.         self.formatter.pop_font()
  222.         self.nofill = max(0, self.nofill - 1)
  223.  
  224.     def start_xmp(self, attrs):
  225.         self.start_pre(attrs)
  226.         self.setliteral('xmp') # Tell SGML parser
  227.  
  228.     def end_xmp(self):
  229.         self.end_pre()
  230.  
  231.     def start_listing(self, attrs):
  232.         self.start_pre(attrs)
  233.         self.setliteral('listing') # Tell SGML parser
  234.  
  235.     def end_listing(self):
  236.         self.end_pre()
  237.  
  238.     def start_address(self, attrs):
  239.         self.formatter.end_paragraph(0)
  240.         self.formatter.push_font((AS_IS, 1, AS_IS, AS_IS))
  241.  
  242.     def end_address(self):
  243.         self.formatter.end_paragraph(0)
  244.         self.formatter.pop_font()
  245.  
  246.     def start_blockquote(self, attrs):
  247.         self.formatter.end_paragraph(1)
  248.         self.formatter.push_margin('blockquote')
  249.  
  250.     def end_blockquote(self):
  251.         self.formatter.end_paragraph(1)
  252.         self.formatter.pop_margin()
  253.  
  254.     # --- List Elements
  255.  
  256.     def start_ul(self, attrs):
  257.         self.formatter.end_paragraph(not self.list_stack)
  258.         self.formatter.push_margin('ul')
  259.         self.list_stack.append(['ul', '*', 0])
  260.  
  261.     def end_ul(self):
  262.         if self.list_stack: del self.list_stack[-1]
  263.         self.formatter.end_paragraph(not self.list_stack)
  264.         self.formatter.pop_margin()
  265.  
  266.     def do_li(self, attrs):
  267.         self.formatter.end_paragraph(0)
  268.         if self.list_stack:
  269.             [dummy, label, counter] = top = self.list_stack[-1]
  270.             top[2] = counter = counter+1
  271.         else:
  272.             label, counter = '*', 0
  273.         self.formatter.add_label_data(label, counter)
  274.  
  275.     def start_ol(self, attrs):
  276.         self.formatter.end_paragraph(not self.list_stack)
  277.         self.formatter.push_margin('ol')
  278.         label = '1.'
  279.         for a, v in attrs:
  280.             if a == 'type':
  281.                 if len(v) == 1: v = v + '.'
  282.                 label = v
  283.         self.list_stack.append(['ol', label, 0])
  284.  
  285.     def end_ol(self):
  286.         if self.list_stack: del self.list_stack[-1]
  287.         self.formatter.end_paragraph(not self.list_stack)
  288.         self.formatter.pop_margin()
  289.  
  290.     def start_menu(self, attrs):
  291.         self.start_ul(attrs)
  292.  
  293.     def end_menu(self):
  294.         self.end_ul()
  295.  
  296.     def start_dir(self, attrs):
  297.         self.start_ul(attrs)
  298.  
  299.     def end_dir(self):
  300.         self.end_ul()
  301.  
  302.     def start_dl(self, attrs):
  303.         self.formatter.end_paragraph(1)
  304.         self.list_stack.append(['dl', '', 0])
  305.  
  306.     def end_dl(self):
  307.         self.ddpop(1)
  308.         if self.list_stack: del self.list_stack[-1]
  309.  
  310.     def do_dt(self, attrs):
  311.         self.ddpop()
  312.  
  313.     def do_dd(self, attrs):
  314.         self.ddpop()
  315.         self.formatter.push_margin('dd')
  316.         self.list_stack.append(['dd', '', 0])
  317.  
  318.     def ddpop(self, bl=0):
  319.         self.formatter.end_paragraph(bl)
  320.         if self.list_stack:
  321.             if self.list_stack[-1][0] == 'dd':
  322.                 del self.list_stack[-1]
  323.                 self.formatter.pop_margin()
  324.  
  325.     # --- Phrase Markup
  326.  
  327.     # Idiomatic Elements
  328.  
  329.     def start_cite(self, attrs): self.start_i(attrs)
  330.     def end_cite(self): self.end_i()
  331.  
  332.     def start_code(self, attrs): self.start_tt(attrs)
  333.     def end_code(self): self.end_tt()
  334.  
  335.     def start_em(self, attrs): self.start_i(attrs)
  336.     def end_em(self): self.end_i()
  337.  
  338.     def start_kbd(self, attrs): self.start_tt(attrs)
  339.     def end_kbd(self): self.end_tt()
  340.  
  341.     def start_samp(self, attrs): self.start_tt(attrs)
  342.     def end_samp(self): self.end_tt()
  343.  
  344.     def start_strong(self, attrs): self.start_b(attrs)
  345.     def end_strong(self): self.end_b()
  346.  
  347.     def start_var(self, attrs): self.start_i(attrs)
  348.     def end_var(self): self.end_i()
  349.  
  350.     # Typographic Elements
  351.  
  352.     def start_i(self, attrs):
  353.         self.formatter.push_font((AS_IS, 1, AS_IS, AS_IS))
  354.     def end_i(self):
  355.         self.formatter.pop_font()
  356.  
  357.     def start_b(self, attrs):
  358.         self.formatter.push_font((AS_IS, AS_IS, 1, AS_IS))
  359.     def end_b(self):
  360.         self.formatter.pop_font()
  361.  
  362.     def start_tt(self, attrs):
  363.         self.formatter.push_font((AS_IS, AS_IS, AS_IS, 1))
  364.     def end_tt(self):
  365.         self.formatter.pop_font()
  366.  
  367.     def start_a(self, attrs):
  368.         href = ''
  369.         name = ''
  370.         type = ''
  371.         for attrname, value in attrs:
  372.             value = value.strip()
  373.             if attrname == 'href':
  374.                 href = value
  375.             if attrname == 'name':
  376.                 name = value
  377.             if attrname == 'type':
  378.                 type = value.lower()
  379.         self.anchor_bgn(href, name, type)
  380.  
  381.     def end_a(self):
  382.         self.anchor_end()
  383.  
  384.     # --- Line Break
  385.  
  386.     def do_br(self, attrs):
  387.         self.formatter.add_line_break()
  388.  
  389.     # --- Horizontal Rule
  390.  
  391.     def do_hr(self, attrs):
  392.         self.formatter.add_hor_rule()
  393.  
  394.     # --- Image
  395.  
  396.     def do_img(self, attrs):
  397.         align = ''
  398.         alt = '(image)'
  399.         ismap = ''
  400.         src = ''
  401.         width = 0
  402.         height = 0
  403.         for attrname, value in attrs:
  404.             if attrname == 'align':
  405.                 align = value
  406.             if attrname == 'alt':
  407.                 alt = value
  408.             if attrname == 'ismap':
  409.                 ismap = value
  410.             if attrname == 'src':
  411.                 src = value
  412.             if attrname == 'width':
  413.                 try: width = int(value)
  414.                 except ValueError: pass
  415.             if attrname == 'height':
  416.                 try: height = int(value)
  417.                 except ValueError: pass
  418.         self.handle_image(src, alt, ismap, align, width, height)
  419.  
  420.     # --- Really Old Unofficial Deprecated Stuff
  421.  
  422.     def do_plaintext(self, attrs):
  423.         self.start_pre(attrs)
  424.         self.setnomoretags() # Tell SGML parser
  425.  
  426.     # --- Unhandled tags
  427.  
  428.     def unknown_starttag(self, tag, attrs):
  429.         pass
  430.  
  431.     def unknown_endtag(self, tag):
  432.         pass
  433.  
  434.  
  435. def test(args = None):
  436.     import sys, formatter
  437.  
  438.     if not args:
  439.         args = sys.argv[1:]
  440.  
  441.     silent = args and args[0] == '-s'
  442.     if silent:
  443.         del args[0]
  444.  
  445.     if args:
  446.         file = args[0]
  447.     else:
  448.         file = 'test.html'
  449.  
  450.     if file == '-':
  451.         f = sys.stdin
  452.     else:
  453.         try:
  454.             f = open(file, 'r')
  455.         except IOError, msg:
  456.             print file, ":", msg
  457.             sys.exit(1)
  458.  
  459.     data = f.read()
  460.  
  461.     if f is not sys.stdin:
  462.         f.close()
  463.  
  464.     if silent:
  465.         f = formatter.NullFormatter()
  466.     else:
  467.         f = formatter.AbstractFormatter(formatter.DumbWriter())
  468.  
  469.     p = HTMLParser(f)
  470.     p.feed(data)
  471.     p.close()
  472.  
  473.  
  474. if __name__ == '__main__':
  475.     test()
  476.